package com.itheima.exception;

import com.itheima.bean.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R handleException(SQLIntegrityConstraintViolationException e){
        e.printStackTrace();
        log.debug("handleExecption执行了===========================");
        String message = e.getMessage();
        System.out.println(message);
        if (message.contains("Duplicate entry")){
         String s= message.split(" ")[2];
         return R.error(s+"已存在！");
        }
        return R.error("未知错误！");
    }


    //自定义异常
    @ExceptionHandler(CustomException.class)
    public R handleCustomException(CustomException e){
        return R.error(e.getMessage());
    }

}
